//
//  LiuViewController.m
//  XiangJi
//
//  Created by apple on 2017/8/9.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "LiuViewController.h"

@interface LiuViewController ()<NSStreamDelegate>{

    NSMutableData *data;
}

@property (nonatomic,strong) NSString *filePath;

@property (nonatomic,strong) NSString *fileStrPath;

@property (nonatomic,assign) int location;

@end

@implementation LiuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
    
    [btn1 setTitle:@"读" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    [btn1 addTarget:self action:@selector(setUpForFile:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn1];
    
    
    UIButton *btn2 = [[UIButton alloc] initWithFrame:CGRectMake(100, 300, 100, 50)];
    
    [btn2 setTitle:@"写" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    [btn2 addTarget:self action:@selector(setOutForFile:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn2];
    
    [self createTestFile];
}


- (void)createTestFile{
    _filePath = NSHomeDirectory();
    _filePath = [_filePath stringByAppendingPathComponent:@"Documents/test_data.txt"];
    
    NSLog(@"_filePath = %@",_filePath);
    
    NSError *error;
    NSString *msg = @"测试数据，需要的测试数据，测试数据显示。";
    bool  isSuccess = [msg writeToFile:_filePath atomically:true encoding:NSUTF8StringEncoding error:&error];
    if (isSuccess) {
        NSLog(@"数据写入成功了");
    }else{
        NSLog(@"error is %@",error.description);
    }
    
    // 追加数据
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
    [handle seekToEndOfFile];
    NSString *newMsg = @".....我将添加到末尾你处";
    NSData *data = [newMsg dataUsingEncoding:NSUTF8StringEncoding];
    [handle writeData:data];
    [handle closeFile];
}

- (void)setUpForFile:(UIButton *)sender{
    
    if (!_fileStrPath) {
        
        NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:_filePath];
        inputStream.delegate = self;
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [inputStream open];
        
    }else{
    
        NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:_fileStrPath];
        inputStream.delegate = self;
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [inputStream open];
    }
}

- (void)setOutForFile:(UIButton *)sender{

    NSString *strPath = @"/Users/apple/Desktop/stream_ios.txt";
    
    NSOutputStream *writeStream = [[NSOutputStream alloc]initToFileAtPath:strPath append:true];
    
    // 手动创建文件， 如果是系统创建的话， 格式编码不一样。
    bool flag = [@"Ios----->" writeToFile:strPath atomically:true encoding:NSUTF8StringEncoding error:nil];
    if (flag) {
        NSLog(@"创建成功");
    }
    
    writeStream.delegate = self;
    [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [writeStream open];
    
    self.fileStrPath = strPath;

}

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{

    switch (eventCode) {
            
        case NSStreamEventHasSpaceAvailable:{ // 写
            
            NSString *content = [NSString stringWithContentsOfFile:_filePath encoding:NSUTF8StringEncoding error:nil];
            NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
            
            NSOutputStream *writeStream = (NSOutputStream *)aStream;
            [writeStream write:data.bytes maxLength:data.length];
            [aStream close];
            
            // 用buf的还没成功
            
            //          [writeStream write:<#(nonnull const uint8_t *)#> maxLength:<#(NSUInteger)#>]; 乱码形式
            
            break;
        }
        case NSStreamEventHasBytesAvailable:{ // 读
            uint8_t buf[1024];
            NSInputStream *reads = (NSInputStream *)aStream;
            NSInteger blength = [reads read:buf maxLength:sizeof(buf)];
            if (blength != 0) {
                NSData *data = [NSData dataWithBytes:(void *)buf length:blength];
                NSString *msg = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"文件内容如下：----->%@",msg);
            }else{
                [aStream close];
            }
            break;
        }
        case NSStreamEventErrorOccurred:{// 错误处理
            
            NSLog(@"错误处理");
            break;
            
        }
        case NSStreamEventEndEncountered: {
            [aStream close];
            break;
        }
        case NSStreamEventNone:{// 无事件处理
            
            NSLog(@"无事件处理");
            break;
        }
        case  NSStreamEventOpenCompleted:{// 打开完成
            
            NSLog(@"打开文件");
            break;
        }
        default:
            break;
    }
}

@end
